package task;

import app.FileMeta;
import util.DBUtil;
import util.Util;

import java.io.File;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FileSave implements ScanCallback{
    @Override
    public void callback(File dir) {
        File[] children = dir.listFiles();
        List<FileMeta> locals = new ArrayList<>();
        if(children != null){
            for(File child : children){
                locals.add(new FileMeta(child));
            }
        }
        //获取数据库中保存的dir目录的子目录和子文件
        List<FileMeta> metas = query(dir);
        //数据库有本地没有，则删除
        for(FileMeta meta : metas){
            if(!locals.contains(meta)){
                //meta删除
                //1.删除meta信息
                //2.如果meta是文件夹，要将meta的子目录和子文件夹都删除
                delete(meta);
                System.out.println("删除操作执行");
            }
        }
        //本地有，数据库中没有，则做添加
        for(FileMeta meta : locals){
            if(!metas.contains(meta)){
                save(meta);
            }
        }
    }
    private void delete(FileMeta meta){
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "delete from file_meta where (name = ? and path = ? and is_Directory = ?)";
            if(meta.getDir()){
                sql += "or path = ? "+"or path like ?";
            }
            ps = connection.prepareStatement(sql);
            ps.setString(1,meta.getName());
            ps.setString(2,meta.getPath());
            ps.setBoolean(3,meta.getDir());
            if(meta.getDir()){
                ps.setString(4,meta.getPath()+File.separator+meta.getName());
                ps.setString(5,meta.getPath()+File.separator+meta.getName()+"%");
            }
            System.out.printf("删除文件信息，dir=%s\n",meta.getPath()+File.separator+meta.getName());
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("删除文件信息出错，检查delete语句",e);
        } finally {
            DBUtil.close(connection,ps);
        }
    }
    private void save(FileMeta meta){
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "insert into file_meta(name,path,is_directory,size,last_modified,pinyin,pinyin_first)" +
                    "values(?,?,?,?,?,?,?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1,meta.getName());
            statement.setString(2,meta.getPath());
            statement.setBoolean(3, meta.getDir());
            statement.setLong(4,meta.getSize());
            statement.setTimestamp(5,new Timestamp(meta.getLastModified().getTime()));
            statement.setString(6,meta.getPinyin());
            statement.setString(7, meta.getPinyinFirst());
            System.out.printf("insert name=%s,path=%s\n",meta.getName(),meta.getPath());
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection,statement);
        }
    }

    private List<FileMeta> query(File file){
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<FileMeta> list = new ArrayList<>();
        try {
            connection = DBUtil.getConnection();
            String sql = "select name,path,is_directory,size,last_modified from file_meta where path = ?";
            ps = connection.prepareStatement(sql);
            ps.setString(1,file.getPath());
            rs = ps.executeQuery();
            while(rs.next()){
                String name = rs.getString("name");
                String path = rs.getString("path");
                Boolean isDirectory = rs.getBoolean("is_directory");
                Long size = rs.getLong("size");
                Timestamp lastModified = rs.getTimestamp("last_modified");
                FileMeta meta = new FileMeta(name,path,size,new Date(lastModified.getTime()),isDirectory);
                System.out.printf("查询文件信息：name=%s,path=%s,isDirectory=%s,size=%s,lastModified=%s\n",
                        name,path,String.valueOf(isDirectory),String.valueOf(size), Util.parseDate(new Date(lastModified.getTime())));
                list.add(meta);
            }
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("sql出错",e);
        } finally {
            DBUtil.close(connection,ps,rs);
        }
    }

}
